<template>
  <!-- 房源信息档案库 新增/编辑 -->
  <div class="housingArchiveEditPage">
    <CommonTitle titleName="基本信息">
      <template #rightCnBox>
        <div class="titleRight">
          <el-button plain class="button_cancel2" @click="cancelEdit"
            >取消{{ pageType === "edit" ? "编辑" : "录入" }}</el-button
          >
          <el-button
            plain
            class="button_view"
            :disabled="saveDisFlag"
            @click="doSave"
            >保存</el-button
          >
        </div>
      </template>
    </CommonTitle>
    <div class="inpuBox">
      <el-form
        :inline="true"
        :model="baseForm"
        ref="baseFormRef"
        :rules="baseState.rules"
        class="demo-form-inline"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-col :span="23">
            <el-form-item
              :style="
                pageType == 'edit'
                  ? 'width: 92.5%; margin-right: 5px'
                  : 'width: 100%'
              "
              label="资产名称"
              prop="assetsName"
            >
              <el-input
                v-model="baseForm.assetsName"
                placeholder="点击选择"
                :disabled="pageType === 'edit'"
                readonly
                @click="choseAsset"
              />
            </el-form-item>
            <el-button
              v-if="pageType == 'edit'"
              plain
              class="f-r button_edit"
              @click="goAssetsDetail(baseForm.assetsId)"
              >查看信息</el-button
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item
              style="width: 100%"
              label="门牌信息"
              prop="housingNumber"
            >
              <el-input
                v-model="baseForm.housingNumber"
                placeholder="请输入该房源门牌信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item
              style="width: 100%"
              label="房源当前状态"
              prop="status"
            >
              <el-select
                v-model="baseForm.status"
                style="width: 100%"
                placeholder="选择房源当前状态"
              >
                <el-option
                  v-for="item in changeHouseState"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item
              style="width: 100%"
              label="所属业态"
              prop="businessType"
            >
              <el-select
                v-model="baseForm.businessType"
                style="width: 100%"
                placeholder="选择所属业态"
              >
                <el-option
                  v-for="item in houseBusinessTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item style="width: 100%" label="房源用途" prop="useType">
              <el-select
                v-model="baseForm.useType"
                style="width: 100%"
                placeholder="选择房源用途"
                @change="useTypeChange"
              >
                <el-option
                  v-for="item in houseUsingTypeOptionArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7">
            <el-form-item style="width: 100%" label="房源持有面积" prop="area">
              <el-input
                v-model="baseForm.area"
                clearable
                @input="
                  baseForm.area = limitInputNum(baseForm.area, 9, 2, true)
                "
                placeholder="请输入房源持有面积 (㎡)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item
              style="width: 100%"
              label="责任部门"
              prop="departmentName"
            >
              <el-input
                disabled
                v-model="baseForm.departmentName"
                placeholder="请输入责任部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item
              style="width: 100%"
              label="租金定价"
              prop="rentPricing"
            >
              <el-input
                v-model="baseForm.rentPricing"
                clearable
                @input="
                  baseForm.rentPricing = limitInputNum(
                    baseForm.rentPricing,
                    9,
                    2,
                    true
                  )
                "
                placeholder="请输入租金定价 (元)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <CommonTitle titleName="相关文件" />
    <div class="inpuBox docImgBox">
      <el-form
        :inline="true"
        :model="docForm"
        class="demo-form-inline"
        label-position="right"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item style="width: 100%" label="资产实景图">
              <!-- <el-upload
                  :headers="docForm.fileUpHeader"
                  :action="`${actionUrl}bf-assets/file/upload/img`"
                  list-type="picture-card"
                  :before-upload="beforePicUpload"
                  :file-list="docForm.picFileList"
                  :limit="5"
                  :on-exceed="exceedFiles"
                  :on-success="upProblemPicSuccess"
                  :on-remove="removeProblemPic"
              >-->
              <el-upload
                name="img"
                list-type="picture-card"
                :http-request="uploadFile"
                :before-upload="beforePicUpload"
                :file-list="docForm.picFileList"
                :limit="5"
                :on-exceed="exceedFiles"
                :on-success="upProblemPicSuccess"
                :on-remove="removeProblemPic"
              >
                <el-icon><Plus /></el-icon>
                <template #tip>
                  <div class="el-upload__tip" style="width: 175px">
                    只能上传 JPG、PNG 格式， 100M 以内，最多上传 5 张
                  </div>
                </template>
              </el-upload>
              <el-dialog
                v-model="docForm.picDialogVisibleFlag"
                :close-on-click-modal="false"
              >
                <img width="100%" :src="docForm.dialogImageUrl" alt="" />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider border-style="dashed" />
        <el-row>
          <el-col :span="24">
            <el-form-item class="noBgBox" style="width: 100%" label="其他文件">
              <!-- <el-upload
                  class="upload-demo"
                  :headers="docForm.fileUpHeader"
                  accept=".doc,.docx,.pdf,.PDF,.rar,.zip"
                  :action="`${actionUrl}bf-assets/file/upload/document`"
                  :http-request="uploadFile"
                  :before-upload="beforeDocUpload"
                  :file-list="docForm.textFileList"
                  :on-remove="handleTextRemove"
                  :on-success="upTextSuccess"
                  :limit="5"
                  :on-exceed="handleTextExceed"
              >-->
              <el-upload
                class="upload-demo"
                name="document"
                accept=".doc,.docx,.pdf,.PDF,.rar,.zip"
                :http-request="uploadFile"
                :before-upload="beforeDocUpload"
                :file-list="docForm.textFileList"
                :on-remove="handleTextRemove"
                :on-success="upTextSuccess"
                :limit="5"
                :on-exceed="handleTextExceed"
              >
                <el-button type="primary" class="button_edit">上传文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">上传文件需小于2G</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <CommonTitle v-if="pageType === 'edit'" titleName="建档信息" />
    <div class="inpuBox" v-if="pageType === 'edit'">
      <el-form
        :inline="true"
        :model="bookBuildingForm"
        class="demo-form-inline"
        label-position="right"
        label-width="100px"
      >
        <el-row>
          <el-col :span="7">
            <el-form-item style="width: 100%" label="建档时间">
              <el-input
                v-model="baseForm.createTime"
                placeholder="档案创建时间"
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <SelectAssetsDialog
      ref="selectAssetDlgRef"
      @getAssetsInfo="getAssetsInfo"
    />
  </div>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";
import SelectAssetsDialog from "./components/selectAssetsDialog.vue";
import {ref, reactive, onMounted, computed, watch} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  ElForm,
  ElFormItem,
  ElRow,
  ElCol,
  ElSelect,
  ElOption,
  ElImage,
  ElDivider,
  ElDatePicker,
  ElDialog,
  ElUpload,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import dayjs from "dayjs";
import {
  houseUsingTypeOptionArr,
  houseBusinessTypeOptions,
  houseStateOptionsArr,
} from "@/common/dict/dictCollect";
import {getURLhandler, limitInputNum} from "@/common/utils/GlobalUtils";
import { housingApi, fileControlApi } from "@/api/assets";
import { ElLoading } from "element-plus";
import {clearCache} from "@/utils/createRoutes";

const store = useStore();
const saveDisFlag = ref(false);

const route = useRoute();

const getHousingId = getURLhandler(route.path).id;
const pageType = getURLhandler(route.path).pageType;

const router = useRouter();

const actionUrl =
  process.env.NODE_ENV === "development"
    ? "/baseApi/"
    : process.env.VUE_APP_URL;

const changeHouseState = houseStateOptionsArr.filter((n) => {
  return n.label !== "占用";
});

// el-upload 选择文件后
const uploadFile = (file) => {
  let uploadFile = new FormData();
  uploadFile.append("file", file.file);
  uploadFile.append("associationId", getHousingId);
  uploadFile.append("businessType ", 2);
  const loadingInstance = ElLoading.service({
    lock: true,
    text: "Loading",
    background: "rgba(0, 0, 0, 0.7)",
  });

  fileControlApi.uploadImgFile(uploadFile).then((response) => {
    const { code, data, msg } = response;
    if (code == 200) {
      loadingInstance.close();
      let obj = {
        fileId: data.fileId,
        fileType: file.filename === "img" ? 1 : 2, // 1图片 2文件
        businessType: 2,
        associationId: data.associationId, // 新增时不传
        fileName: data.fileName,
        fileUrlKey: data.fileUrlKey,
        fileAddress: data.fileAddress,
      };
      if (file.filename === "document") {
        docForm.postDocsArr.push(obj);
      }
      if (file.filename === "img") {
        docForm.postImgsArr.push(obj);
      }
    } else {
      loadingInstance.close();
      ElMessage({
        type: "error",
        message: msg,
      });
    }
  });
};

const baseFormRef = ref(null);
const baseForm = reactive({
  assetsId: "",
  assetsName: "",
  housingNumber: "",
  businessType: "",
  useType: "",
  area: "",
  departmentName: "",
  status: "",
  createTime: "",
  rentPricing: "",
});
const baseState = reactive({
  rules: {
    assetsName: [
      { required: true, trigger: "change", message: "请选择资产名称" },
    ],
    housingNumber: [
      { required: true, trigger: "blur", message: "请输入门牌信息" },
    ],
    status: [
      { required: true, trigger: "change", message: "请选择房源当前状态" },
    ],
    useType: [{ required: true, trigger: "change", message: "请选择房源用途" }],
    businessType: [
      { required: true, trigger: "change", message: "请选择房源用途" },
    ],
    area: [{ required: true, trigger: "blur", message: "请输入房源持有面积" }],
    rentPricing: [
      { required: false, trigger: "blur", message: "请输入租金定价" },
    ],
  },
});

const useTypeChange = (val) => {
  baseState.rules.rentPricing[0].required = val === 1 ? true : false;
};

// 选择资产相关
const selectAssetDlgRef = ref(null);
const choseAsset = () => {
  selectAssetDlgRef.value.open();
};
const getAssetsInfo = (val) => {
  baseForm.assetsId = val.assetsId;
  baseForm.assetsName = val.assetsName;
};

// 上传相关
const getAccessToken = computed(() => store.state.user.accessToken);
const docForm = reactive({
  fileUpHeader: { Authorization: `${getAccessToken.value}` },
  picFileList: [],
  textFileList: [],
  picDialogVisibleFlag: false,
  dialogImageUrl: "",
  postImgsArr: [],
  postDocsArr: [],
});
const beforePicUpload = (file, index) => {
  const isLt100M = file.size / 1024 / 1024 < 100;
  let isImg = false;
  if (!/^image\/(jpeg|png|jpg)$/.test(file.type)) {
    ElMessage({
      type: "error",
      message: "上传图片仅支持 JPG、PNG、格式!",
    });
  } else {
    isImg = true;
  }
  if (!isLt100M) {
    ElMessage({
      type: "error",
      message: "上传图片大小不能超过 100MB!",
    });
  }
  return isImg && isLt100M;
};
const beforeDocUpload = (file, index) => {
  // file.size (单位为b)
  if (file.size / 1024 / 1024 / 1024 > 2) {
    ElMessage({
      type: "warning",
      message: "您上传的文件大于2G",
    });
    return false;
  }
  return true;
};
const exceedFiles = (files, fileList) => {
  ElMessage({
    type: "error",
    message: "至多可以上传5张图片",
  });
};
const removeProblemPic = (file, fileList) => {
  docForm.postImgsArr.map((n, i) => {
    if (n.fileName == file.name) {
      docForm.postImgsArr.splice(i, 1);
    }
  });
};
const upProblemPicSuccess = (response, file, fileList) => {
  const { code, data, msg } = response;
  if (code == 200) {
    let obj = {
      fileId: data.fileId,
      fileType: 1,
      businessType: 2,
      associationId: data.associationId, // 新增时不传
      fileName: data.fileName,
      fileUrlKey: data.fileUrlKey,
      fileAddress: data.fileAddress,
    };
    docForm.postImgsArr.push(obj);
  } else {
    ElMessage({
      type: "error",
      message: msg,
    });
  }
};
const upTextSuccess = (response, file, fileList) => {
  const { code, data, msg } = response;
  if (code == 200) {
    let obj = {
      fileId: data.fileId,
      fileType: 2, // 1图片 2文件
      businessType: 2, // 1房源业务，2资产业务
      associationId: data.associationId, // 新增时不传
      fileName: data.fileName,
      fileUrlKey: data.fileUrlKey,
      fileAddress: data.fileAddress,
    };
    docForm.postDocsArr.push(obj);
  } else {
    ElMessage({
      type: "error",
      message: msg,
    });
  }
};
const handleTextRemove = (file, fileList) => {
  docForm.postDocsArr.map((n, i) => {
    if (n.fileName == file.name) {
      docForm.postDocsArr.splice(i, 1);
    }
  });
};
const handleTextExceed = (files, fileList) => {
  ElMessage({
    type: "error",
    message: "至多可以上传5个文件",
  });
};

const bookBuildingForm = reactive({
  shortcutsArr: [
    {
      text: "今天",
      value: new Date(),
    },
    {
      text: "昨天",
      value: () => {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        return date;
      },
    },
    {
      text: "一周前",
      value: () => {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        return date;
      },
    },
  ],
});
const disabledDate = (time) => {
  return dayjs(time) > Date.now();
};

// 跳转资产详情页
const goAssetsDetail = (id) => {
  router.push({ path: `/asset/company/assetDetail/${id}` });
};

const doSave = () => {
  baseFormRef.value.validate((vaild) => {
    if (vaild) {
      saveDisFlag.value = true;
      baseForm.files = [...docForm.postImgsArr, ...docForm.postDocsArr];
      if (pageType === "edit") {
        baseForm.housingId = getHousingId;
        housingApi.updateHousing(baseForm).then((res) => {
          const { code, data, msg } = res;
          if (code === '200') {
            ElMessage({
              type: "success",
              message: msg,
            });
            setTimeout(() => {
              router.push({ path: "/asset/company/housingInformation" });
              saveDisFlag.value = false;
            }, 1000);
            clearCache({title:'房源信息录入'});
          } else {
            saveDisFlag.value = false;
          }
        });
      }
      if (pageType === "add") {
        housingApi.addHousing(baseForm).then((res) => {
          const { code, data, msg } = res;
          if (code === '200') {
            ElMessage({
              type: "success",
              message: msg,
            });
            setTimeout(() => {
              router.push({ path: "/asset/company/housingInformation" });
              saveDisFlag.value = false;
            }, 1000);
          } else {
            saveDisFlag.value = false;
          }
        });
      }
    }
  });
};
const iconUrl = require("@/assets/iconImg/warning.png");
const cancelEdit = () => {
  // 确认弹窗
  ElMessageBox.confirm(
    "<img style='width:20px;height:20px;margin-right: 5px;' src=" +
      iconUrl +
      " />是否确认不保存档案已设置的数据？",
    "提示",
    {
      customClass: "deletConfirmBox",
      confirmButtonText: "确认",
      confirmButtonClass: "button_view",
      cancelButtonText: "取消",
      cancelButtonClass: "button_cancel2",
      dangerouslyUseHTMLString: true,
      center: true,
      closeOnClickModal: false,
      showClose: false,
    }
  )
    .then(() => {
      clearCache({title:'房源信息录入'});
      router.push({ path: "/asset/company/assetInformation" });
    })
    .catch(() => {});
};

// 编辑时获取的文件数据转换后赋值
const getTextDataChange = (arr) => {
  // 图片
  let newPicArr = arr.filter((n) => {
    return n.fileType == 1;
  });
  if (newPicArr.length) {
    docForm.picFileList = newPicArr.map((n, i) => {
      let obj = {
        name: n.fileName,
        url: n.fileAddress,
      };
      return obj;
    });
    docForm.postImgsArr = newPicArr;
  }
  // 文件
  let newDocArr = arr.filter((n) => {
    return n.fileType == 2;
  });
  if (newDocArr.length) {
    docForm.docFileList = newDocArr.map((n, i) => {
      let obj = {
        name: n.fileName,
        url: n.fileAddress,
      };
      return obj;
    });
    docForm.postDocsArr = newDocArr;
  }
};

/**
 * 监听form,用户在输入
 */
watch(baseForm,(value)=>{
    store.commit("setHousingResourcesForm", baseForm);
},{deep:true})

const initForm = () => {
    if (store.state.collaborativeApproval.housingResourcesForm) {
        for (let key in store.state.collaborativeApproval.housingResourcesForm) {
            for (let key2 in baseForm) {
                baseForm[key] = store.state.collaborativeApproval.housingResourcesForm[key];
            }
        }
    }
};



onMounted(() => {
  if (pageType === "edit") {
    // 编辑时查询
    housingApi.getHousingDetail(getHousingId).then((res) => {
      const { code, data, msg } = res;
      if (code == 200) {
        Object.keys(baseForm).forEach((key) => {
          baseForm[key] = data[key];
        });
        baseState.rules.rentPricing[0].required =
          baseForm.useType === 1 ? true : false;
        getTextDataChange(data.files);
      }
    });
  }

  if(pageType !== "edit"){
      initForm();
  }
});
</script>

<style lang="scss" scoped>
.housingArchiveEditPage {
  .titleRight {
    flex: 1;
    display: flex;
    justify-content: flex-end;
  }
  .inpuBox {
    padding: 32px 76px 15px;
    border-radius: 10px;
    border: 1px solid #e3e7f1;
    margin-bottom: 38px;
  }
}
</style>

<style lang="scss" scoped>
.housingArchiveEditPage {
  .inpuBox {
    :deep(.demo-form-inline) {
      .el-form-item {
        margin-bottom: 34px;
        .el-form-item__label {
          font-weight: 500;
          font-size: 16px;
          font-family: SourceHanSansMedium;
        }
        .el-form-item__content {
          .el-date-editor.el-input,
          .el-date-editor.el-input__wrapper {
            width: 100%;
            .el-input__wrapper {
              width: 100%;
            }
          }
        }
      }
      .noBgBox {
        .el-form-item__content {
          background: none;
        }
      }
    }
  }
  :deep(.docImgBox) {
    .el-upload-list__item-actions {
      .el-upload-list__item-preview {
        display: none;
      }
      .el-upload-list__item-delete {
        margin-left: 2px;
      }
    }
    .upload-demo {
      width: 100%;
      .el-upload-list {
        .el-upload-list__item {
          width: 220px;
          margin-right: 80px;
          float: left;
        }
      }
    }
  }
}
</style>
